﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using Camc.Duct.TaskProcess.Dto;
using Camc.Duct.TaskProcess.Dto.Worker;
using Camc.Duct.TaskProcess.TaskLine;
using Camc.Duct.TaskProcess.Worker;

namespace Camc.Duct.TaskProcess
{
	public class WorkingTeamAppService:CrudAppService<WorkingTeam, WorkingTeamDto,int,GetAllWorkingTeamInput,CreateWorkingTeam,UpdateWorkingTeam>
	{
		private readonly IRepository<WorkingTeam, int> _workingTeamRepository;
		private readonly IRepository<LineInstance, Guid> _lineInstanceRepository;

		public WorkingTeamAppService(IRepository<WorkingTeam, int> repository, IRepository<LineInstance, Guid> lineInstanceRepository) : base(repository)
		{
			_workingTeamRepository = repository;
			_lineInstanceRepository = lineInstanceRepository;
		}

		public List<WorkingTeamProportion> GetProportions()
		{
			var query = _workingTeamRepository.GetAllIncluding(c => c.LineInstances).Select(c =>
				new WorkingTeamProportion
				{
					WorkingTeamId = c.Id,
					WorkingName = c.DisplayName,
					NumOfTask = c.LineInstances.Count(d => d.State == TaskLineState.进行),
					NumOfQuantity = c.LineInstances.Where(d=>d.State == TaskLineState.进行).Sum(e=>e.Quantity)

				});

			return query.ToList();
		}

		public void AddInstancesToWorkingTeam(List<AddInstancesToWorkingTeamInput> inputs)
		{
			foreach (var input in inputs)
			{
				var instance = _lineInstanceRepository.Get(input.InstanceId);
				instance.WorkingTeamId = input.WorkTeamaId;
			}
		}

		public void ChangeInstancesToWorkingTeam(AddInstancesToWorkingTeamInput input)
		{
			var instance = _lineInstanceRepository.Get(input.InstanceId);
			instance.WorkingTeamId = input.WorkTeamaId;
		}

		public List<GetLineInstanceForDistributeOutput> GetAllInstanceOfDistribute(bool onlyUndistributed = true)
		{

			var query = _lineInstanceRepository.GetAllIncluding(c => c.Historys,d=>d.WorkingTeam);

			if(onlyUndistributed)
			{
				query = query.Where(c =>
					c.State == TaskLineState.进行 && c.Historys.Count == 1 && (c.WorkingTeamId == null));
			}
			else
			{
				query = query.Where(c =>
					c.State == TaskLineState.进行 || c.State== TaskLineState.暂停);
			}

			var instances = query.OrderByDescending(c=>c.LastModificationTime)
				.Select(c => new GetLineInstanceForDistributeOutput
				{
					Quantity = c.Quantity,
					ProductionDrawingCode = c.ProductionDrawingCode,
					TaskModel = c.TaskModel,
					DeliveryTime = c.DeliveryTime,
					Id = c.Id,
					ProductionSpecial = c.ProductionSpecial,
					ProcessStartTime = c.CreationTime,
					WorkingTeamName = c.WorkingTeam.DisplayName
				}).ToList();

			return instances;
		}

	}
}
